﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Web;
using blackhouse.Data;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Web;

namespace blackhouse.Aparts.Web.Navigation {
    public class CmsUrlHelper {

        #region Fields

        private HttpContext context;
        private MsSqlAdoDataHelper dataHelper;
        private CmsUrlLine[] data;
        private string dictionary;

        #endregion

        #region Properties

        private CmsUrlLine[] Data {
            get {
                if (this.data == null)
                    this.data = this.GetData();
                return this.data;
            }
        }

        #endregion

        #region Constructors

        public CmsUrlHelper(string urlGroup) {
            this.dictionary = urlGroup;
            string connectionString = ConfigurationManager.AppSettings["MSSQLConnectionString"];
            this.dataHelper = new MsSqlAdoDataHelper(connectionString);
            this.context = HttpContext.Current;
        }

        #endregion

        #region Methods

        public string GetUrl(int recordId) {
            CmsUrlLine line = this.Data.FirstOrDefault(l => l.RecordId == recordId && l.Language == CultureInfo.CurrentCulture.Name && l.DictionaryId == this.dictionary);
            if (line != null)
                return line.Url;
            else return String.Empty;
        }

        private CmsUrlLine[] GetData() {
            CmsUrlLine[] data = this.TryGetDataFromCache();
            if (data == null) {
                data = this.GetDataFromDb();
                this.SetCache(data);
            }
            return data;
        }

        private CmsUrlLine[] GetDataFromDb() {
            this.dataHelper.Reset();
            this.dataHelper.ProcedureName = "bhp_Urls";
            IDataReader reader = this.dataHelper.Execute();
            List<CmsUrlLine> data = new List<CmsUrlLine>();
            while (reader.Read()) {
                data.Add(this.ReadUrlFields(reader));
            }
            reader.Close();
            return data.ToArray();
        }

        private CmsUrlLine ReadUrlFields(IDataReader reader) {
            CmsUrlLine line = new CmsUrlLine();
            line.DictionaryId = Convert.ToString(reader["DictionaryId"]);
            line.Language = Convert.ToString(reader["Language"]);
            line.RecordId = Convert.ToInt32(reader["RecordId"]);
            line.Url = Convert.ToString(reader["Url"]);
            return line;
        }

        private void SetCache(CmsUrlLine[] data) {
            if (context == null || context.Cache == null) return;
            this.context.Cache.Add("CmsUrl", data, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(20), System.Web.Caching.CacheItemPriority.Default, null);
        }

        private void RemoveDataStoreage() {
            this.data = null;
            if (context == null || context.Cache == null) return;
            this.context.Cache.Remove("CmsUrl");
        }

        private CmsUrlLine[] TryGetDataFromCache() {
            if (context == null || context.Cache == null) return null;
            return context.Cache["CmsUrl"] as CmsUrlLine[];
        }

        public void SaveUrl(int recordId, string url) {
            this.dataHelper.Reset();
            this.dataHelper.ProcedureName = "bhp_UrlsSave";
            this.dataHelper.AddParameter("DictionaryId", this.dictionary);
            this.dataHelper.AddParameter("Language", CultureInfo.CurrentCulture.Name);
            this.dataHelper.AddParameter("Url", url);
            this.dataHelper.AddParameter("RecordId", recordId, DbType.Int32);
            this.dataHelper.ExecuteWithoutResult();
        }

        public void AddCmsUrl(string friendlyUrl, string rewriteUrl) {

            int siteId = 1;
            Guid siteGuid = Guid.Empty;

            SiteSettings ss = CacheHelper.GetCurrentSiteSettings();
            if (ss != null) {
                siteId = CacheHelper.GetCurrentSiteSettings().SiteId;
                siteGuid = ss.SiteGuid;
            }

            string newUrl = friendlyUrl.Replace("~/", string.Empty);
            if (newUrl[0] == '/')
                newUrl = newUrl.Substring(1);

            FriendlyUrl friendlyUrlObj = new FriendlyUrl(siteId, newUrl);

            if (!friendlyUrlObj.FoundFriendlyUrl) {
                if (WebPageInfo.IsPhysicalWebPage("~/" + friendlyUrl)) {
                    return;
                }
            }

            if (rewriteUrl[0] != '~') {
                if (rewriteUrl[0] == '/')
                    rewriteUrl = '~' + rewriteUrl;
                else
                    rewriteUrl = "~/" + rewriteUrl;
            }

            if (!friendlyUrlObj.FoundFriendlyUrl) {
                if ((friendlyUrl.Length > 0) && (!WebPageInfo.IsPhysicalWebPage("~/" + friendlyUrl))) {
                    FriendlyUrl newFriendlyUrl = new FriendlyUrl();
                    newFriendlyUrl.SiteId = siteId;
                    newFriendlyUrl.SiteGuid = siteGuid;
                    newFriendlyUrl.PageGuid = CacheHelper.GetCurrentPage().PageGuid;
                    newFriendlyUrl.Url = newUrl;
                    newFriendlyUrl.RealUrl = rewriteUrl;

                    newFriendlyUrl.Save();
                }

            }

        }

        #endregion

    }
}